package sim.states;

import ctf.network.ProtocolError;
import sim.ISimulator;
import sim.ISimulator.State;
import utils.CTFGrammar;
import utils.Point2D_DataPackage;
import utils.Trees_DataPackage;

/**
 * State to manage the creation of new rounds.  Responds with the positions of all trees.
 * @author N. Bhatia, A. Butt, N. Evans, C. Levesque, P. OKeefe
 *
 */
public class NewRoundState extends AbstractState {
	private int numFlagsPlaced = 0;

	public NewRoundState(ISimulator simulator) {
		super(simulator);
	}

	@Override
	public void request(int clientId, String request) throws ProtocolError {
		String[] splitString = request.split(" ");
		if (splitString.length == 1 && splitString[0].equals("getTrees")) {
			//this.simulator.setState(clientId, State.PLACE_FLAG);
			Trees_DataPackage treesdp = new Trees_DataPackage();
			treesdp.trees = this.simulator.getTrees();
			this.simulator.respond(clientId, treesdp.encode());
		} else if (splitString.length == 2 && splitString[0].equals("placeFlag")) {
			Point2D_DataPackage flagPoint = new Point2D_DataPackage();
			flagPoint.decode(splitString[1]);
			this.simulator.placeFlag(clientId, flagPoint.point);
			this.simulator.setState(clientId, State.PLAY);
			this.simulator.respond(clientId, "ok");
			numFlagsPlaced++;
			if (numFlagsPlaced == 2) {
				this.simulator.play();
				numFlagsPlaced = 0;
			}
		} else {
			throw new ProtocolError(CTFGrammar.GET_TREES, request);
		}

	}
	
	@Override
	public void reset() {
		numFlagsPlaced = 0;
	}
	
}
